//
//  FHUserAccount.swift
//  WeiBo
//
//  Created by qfh on 16/7/10.
//  Copyright © 2016年 qiufuhe. All rights reserved.
//

import UIKit

class FHUserAccount: NSObject, NSCoding{

    /// access 码
    var access_token: String?
    
    /// 过期时间
    var expires_in: NSTimeInterval = 0 {
    
        didSet {
            
            expiresDate = NSDate().dateByAddingTimeInterval(expires_in)
        
        
        }
    
        
    }
    
    /// 过期日期
    var expiresDate: NSDate?
    
    /// uid
    var uid: Int64 = 0
    /// 姓名
    var name: String?
    /// 头像地址
    var avatar_large: String?
    
    
    init(dict: [String : AnyObject]) {
        super.init()
        
        setValuesForKeysWithDictionary(dict)
        
        
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }

   /// 重写description
   override var description: String {
        
        let keys = ["access_token", "expiresDate", "uid", "name", "avatar_large"]
    
        return dictionaryWithValuesForKeys(keys).description

        
        
    }
    
    // MARK: - 数据存储
    
    /**
     归档
     
     - parameter aCoder:
     */
    func encodeWithCoder(aCoder: NSCoder) {
     
        aCoder.encodeObject(access_token, forKey: "access_token")
        
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        
        aCoder.encodeObject(name, forKey: "name")
        
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        
        aCoder.encodeInt64(uid, forKey: "uid")
        
        
        
    }
    
    /**
     解档
     
     */
    
    required  init?(coder aDecoder: NSCoder) {
        
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        
        uid = aDecoder.decodeInt64ForKey("uid")
        
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        
        name = aDecoder.decodeObjectForKey("name") as? String
    
        
        
    }
    
    /**
    *  保存用户对象
    */
    
    func saveUserAccount() ->Bool {
    
    
 /// 存储路径
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.xxx")
     
        return NSKeyedArchiver.archiveRootObject(self, toFile: path)

    }
    /**
     读取数据
     
     */
    
    class func loadUserAccount() -> FHUserAccount? {
    
        /// 存储路径
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.xxx")
    
        return NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? FHUserAccount
        
    }
    
    
}

